package thread.unit2.learntsafe;

/**
 *使用同步方法的方式解决接口多线程的线程安全问题
 */

public class ThreadSafeDemo3 implements Runnable{
    private  int ticket = 100;

    public static void main(String[] args) {
        ThreadSafeDemo3 threadSafeDemo3 = new ThreadSafeDemo3();
        Thread w1 = new Thread(threadSafeDemo3,"窗口一");
        Thread w2 = new Thread(threadSafeDemo3,"窗口二");
        Thread w3 = new Thread(threadSafeDemo3,"窗口三");
        w1.start();
        w2.start();
        w3.start();
    }

    @Override
    public void run() {
        while (true) {
            show();
        }
    }

    //同步实现方式二：同步方法
    public synchronized void show() {//此时同步监视器为：this
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "卖票，当前票号：" + ticket);
            ticket--;
        }
    }
}
